import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown,Card, Menu,Switch,Select,Col,Row,Input,Divider } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule,resetRule } from './service';
import { selectEnum } from '@/utils/utils';
import Styles from './index.less';
import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
interface TableListProps extends FormComponentProps {}
const FormItem = Form.Item;

const TableList: React.FC<TableListProps> = props => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
    const { form } = props
    const actionRef = useRef<ActionType>();
    const buildEnum = (option: any) => {
        let defaultEnum = {all: { text: '全部' } };
        option?.map((val: any, index: number) => {
            defaultEnum[parseInt(val.key)] = { text: val.text };
        });
       // defaultEnum['all'] = { text: '全部' }
        
        console.log(444,defaultEnum)
        return defaultEnum;
    }
    const buildOption = (option: any) => {
        let defaultEnum = [{ key: '', text: '全部' }];
        option?.map((val: any, index: number) => {
            defaultEnum.push({ key: val.key, text: val.text });
        });
        return defaultEnum;
    };
    let groupOption = buildOption(apiState?.common?.platformOption);
    let groupEnum = buildEnum(apiState?.common?.platformOption);
    // 列定义
    const columns: ProColumns<TableListItem>[] = [
        // {
        //     title: formatMessage({ id: 'app.base.platform_number' }),
        //     dataIndex: 'platform_id',
        // },
        {
            title: formatMessage({ id: 'app.base.platform_name' }),
            dataIndex: 'platform_id',
            filters:false,
            valueEnum: selectEnum(apiState.common.platformOption),
        },
        {
            title: formatMessage({ id: 'app.base.client_name' }),
            dataIndex: 'name',
            
        },
        {
            title: 'App ID',
            dataIndex: 'app_id',
        },
        {
            title: 'App Key',
            dataIndex: 'app_secret',
            hideInSearch: true,
        },
        // {
        //     title: formatMessage({ id: 'app.base.number_of_requests' }),
        //     dataIndex: 'request_count',
        //     hideInSearch: true,
        // },
        {
            title: formatMessage({ id: 'app.base.enabled_state' }),
            dataIndex: '',
            render: (_, record) => (
              <Switch checked={record.is_enable} onChange={async () => {
                let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
                s && actionRef.current?.reload();
              }} />
            )
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                <a
                    onClick={() => {
                        handleDataModalVisible(true);
                        setDataFormValues(record);
                        setIsUpdate(true);
                    }}
                >
                    {formatMessage({ id: 'app.base.update' })}
                </a>
                <Divider type="vertical"></Divider>
                <a
                    onClick={() => {
                        TsxHelper.showKeyConfirm(
                            'danger',
                            resetItem,
                            {id:record.id},
                            () => {
                                // setRowKeys([]);
                                // action.reload();
                            }
                        )
                        //resetItem({id:record.id})  
                    }}
                >
                    {formatMessage({ id: 'app.base.reset_key' })}
                </a>
                <Divider type="vertical"></Divider>
                <a
                    onClick={async e => {
                        TsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            record.id,
                            () => {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            }
                        )
                    }}
                >
                    {formatMessage({ id: 'app.base.delete' })}
                </a>
                
                </>
            ),
        },
    ];

    // 请求接口数据, 设置组件状态
    const getTableData = (params:any) => {
        return queryRule(params).then((res:any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }
    const [searchParams, setSearch] = useState<any>({ common: {} });
    // 表单提交
    const handleSubmitDataForm = (value:any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }
    const handleSearch = (params?: any) => {
        form.validateFields((err, fieldsValue) => {
            console.log(fieldsValue.channel_type)
            params = {
                group_id: fieldsValue.group_id !== undefined ? fieldsValue.group_id : '',
                name: fieldsValue.name !== undefined ? fieldsValue.name : '',
                app_id: fieldsValue.app_id !== undefined ? fieldsValue.app_id : '',
                _timestamp:new Date()
            }
        })
        setSearch(params)
    };
    const handleFormReset = () => {
        form.resetFields();
        //setId(undefined)
        handleSearch();
    }

    return (
        <PageHeaderWrapper>
            <Card style={{ marginBottom: 20, border: 'none' }}>
                <Form className={Styles.search}>
                    <Row style={{ marginLeft: -8, marginRight: -8 }}>
                        <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6} style={{ paddingLeft: 8, paddingRight: 8 }}>
                            <FormItem label={'平台名称'}>
                                {form.getFieldDecorator('group_id', {
                                })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
                                    {apiState?.common.platformOption && TsxHelper.buildSelectOption(groupOption)}
                                </Select>)}
                            </FormItem>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6} style={{ paddingLeft: 8, paddingRight: 8 }}>
                            <FormItem label={'客户端名称'}>
                                {form.getFieldDecorator('name', {
                                })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
                            </FormItem>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6} style={{ paddingLeft: 8, paddingRight: 8 }}>
                            <FormItem label={'App ID'}>
                                {form.getFieldDecorator('app_id', {
                                })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
                            </FormItem>
                        </Col>
                        <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6} style={{ float: 'right', paddingLeft: 8, paddingRight: 8 }}>
                            <div style={{ float: 'right' }}>
                                <Button type="primary" onClick={() => {
                                    handleSearch()
                                }}
                                > 查询</Button>
                                <Button style={{ marginLeft: '20px' }} onClick={() => handleFormReset()}>重置</Button>
                            </div>
                        </Col>
                    </Row>

                </Form>
            </Card>
          <ProTable<TableListItem>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            search={false}
            toolBarRender={(action, { selectedRows }) => [
              selectedRows && selectedRows.length > 0 && (
                  <Dropdown
                      overlay={
                        <Menu
                            onClick={async e => {
                                if (e.key === 'remove') {
                                    TsxHelper.showDeleteConfirm(
                                        'danger',
                                        handleRemove,
                                        selectedRows,
                                        () => {
                                            setRowKeys([]);
                                            action.reload();
                                        }
                                    )
                                }
                            }}
                            selectedKeys={[]}
                        >
                          <Menu.Item key="remove">
                              {formatMessage({ id: 'app.base.batch_delete' })}
                          </Menu.Item>
                        </Menu>
                      }
                  >
                    <Button>
                        {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                    </Button>
                  </Dropdown>
              ),
              // @ts-ignore
              <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); handleDataModalVisible(true);}}>
                {formatMessage({ id: 'app.base.create' })}
              </Button>,
          ]}
            tableAlertRender={false}
            request={params => getTableData(params)}
            params={searchParams}
            columns={columns}
            rowSelection={false}
            />
            <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={apiState.common || {}}
                onSubmit={ async formValue => handleSubmitDataForm(formValue) }
                onCancel={() => handleDataModalVisible(false)}
            />
              {
                  previewModelVisible && (
                      <PreviewForm
                          previewModelVisible={previewModelVisible}
                          onVisibleModel={handlePreviewModalVisible}
                          previewImg={previewImg}
                      />
                  )
              }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows;
    return RequestHelper.bdExec({
        fn: removeRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};
const resetItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: resetRule, args: fields, successMsg: '重置成功', failMsg: '重置失败请重试！' });
};
const handleUpdateItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

export default Form.create<TableListProps>()(TableList);
